﻿using System;
using System.Linq.Expressions;
using BabyShop.WebSite.Exts.Extensions;

namespace BabyShop.WebSite.Data.Conventions.Properties
{
    public class DateEqualsConvention : PropertyExpressionConventionBase
    {
        public DateEqualsConvention() : base(10) { }

        public override Expression BuildExpression(BuildPropertyExpressionContext context) {
            if (context.Property.PropertyType.NotIn(typeof(DateTime), typeof(DateTime?))) return null;

            var queryValue = context.ValueProvider.GetQueryValue(context.Property.Name, typeof(DateTime));
            context.ModelState.AddIfValueNotNull(context.Property.Name, queryValue.ModelState);
            context.IsHandled = queryValue.ModelState != null;
            if (queryValue.Value == null) return null;

            var date = ((DateTime)queryValue.Value).Date;
            var expression = context.PropertyExpression;
            if (expression.Type == typeof(DateTime?)) expression = expression.Property("Value");
            return expression.Property("Date").Equal(Expression.Constant(date));
        }
    }
}